package cn.thoughtworks.school.services;

import cn.thoughtworks.school.feign.UserCenterFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserCenterService {
  @Autowired
  private UserCenterFeign userCenterFeign;
  @Autowired
  private PublishService publishService;

  public Map getUserInfo(Long userId) {
    Map user = userCenterFeign.getUserById(userId);
    boolean isPublisher = publishService.isPublisherInOrganization(userId, Long.parseLong(user.get("currentOrganizationId").toString()));
    user.put("isPublisher", isPublisher);
    return user;
  }

  public Long getUserCurrentOrganizationId(Long id) {
    Map user = userCenterFeign.getUserById(id);
    return Long.valueOf(user.get("currentOrganizationId").toString());
  }

  public List getUsersByIds(List<Long> userIds) {
    if (userIds.isEmpty()) {
      return new ArrayList();
    }
    String ids = userIds.stream().map(String::valueOf).collect(Collectors.joining(","));
    return userCenterFeign.getUsersByIds(ids);
  }

  public List<Map> getUserByNameOrEmail(String username) {
    return userCenterFeign.getUserByUserNameOrEmail(username);
  }

  public boolean hasPublishRole(Long id) {
    return (boolean) getUserInfo(id).get("isPublisher");
  }

  public boolean hasAdminRole(Long id) {
    return getUserInfo(id).get("roles").toString().contains("9");
  }
}
